<?php

class UserController extends AppController {

	var $paginate = array(
		'User' => array('order' => 'User.id DESC', 'limit' => 10)
	);

	public function index() {
		$this->User->recursive = 0;
		$this->set('users', $this->paginate());
	}

	public function view($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			$this->setFlashError('Záznam nebol nájdený.');
			$this->redirect(array('action' => 'index'));
		}
		$this->set('user', $this->User->read(null, $id));
	}

	public function add() {
		if ($this->request->is('post')) {
			$this->User->create();
			if (trim($this->request->data['User']['password']) == '') {
				$this->setFlashError('Nezadali ste heslo.');
			} else {
				if ($this->User->save($this->request->data)) {
					$person = $this->Person->read(null, $this->request->data['User']['fk_person_id']);
					
					if ($person && isset($person['Person']['email']) && $person['Person']['email'] != '') {
						$message = '<p>Dobrý deň,</p>';
						$message .= '<p>v systéme MNH group (<a href="http://www.mnh.sk">mnh.sk</a>) Vám bolo vytvorené konto.</p>';
						$message .= '<p>Používateľské meno: ' . $this->request->data['User']['username'] . '</p>';
						$message .= '<p>Heslo: ' . $this->request->data['User']['password'] . '</p>';
						$message .= '<p>Prajeme Vám pekný deň.</p>';
						$this->sendMail($person['Person']['email'], 'Nové konto v systéme mnh.sk', $message);
					}
					
					$this->setFlashSuccess('Záznam bol uložený do databázy.');
					$this->redirect(array('action' => 'index'));
				} else {
					$this->setFlashError('Záznam sa nepodarilo uložiť do databázy.');
				}
			}
		}
		$personList = $this->Person->find("all", array('order' => 'Person.full_name'));
		$this->set('personList', $personList);
	}

	public function edit($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			$this->setFlashError('Záznam nebol nájdený.');
			$this->redirect(array('action' => 'index'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->request->data['User']['change_password'] == 0) {
				unset($this->request->data['User']['password']);
			} else {
				if ($this->request->data['User']['password'] == '') {
					$this->setFlashError('Záznam sa nepodarilo uložiť do databázy. Musíte zadať nové heslo.');
					$this->redirect(array('action' => 'edit', $id));
				}
			}
			if ($this->User->save($this->request->data)) {
				$this->setFlashSuccess('Záznam bol uložený do databázy.');
				$this->redirect(array('action' => 'index'));
			} else {
				$this->setFlashError('Záznam sa nepodarilo uložiť do databázy.');
			}
		} else {
			$this->request->data = $this->User->read(null, $id);
			if ($this->request->data) {
				unset($this->request->data['User']['password']);
			}
		}
		$personList = $this->Person->find("all");
		$this->set('personList', $personList);
	}

	public function editProfile() {
		$this->User->id = $this->Session->read('Auth.User.id');
		if (!$this->User->exists()) {
			$this->setFlashError('Záznam nebol nájdený.');
			$this->redirect(array('action' => 'index'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			$user = $this->User->read(null, $this->Session->read('Auth.User.id'));
			if ($user['User']['password'] !== AuthComponent::password($this->request->data['User']['actual_password'])) {
				$this->setFlashError('Nezadali ste správne súčasné heslo.');
			} else {
				if (trim($this->request->data['User']['password']) == '') {
					$this->setFlashError('Nezadali ste nové heslo.');
				} else {
					if ($this->User->save($this->request->data)) {
						$this->setFlashSuccess('Záznam bol uložený do databázy.');
							$this->redirect(array('controller' => 'pages', 'action' => 'index'));
					} else {
						$this->setFlashError('Záznam sa nepodarilo uložiť do databázy.');
					}
				}
			}
		} else {
			$this->request->data = $this->User->read(null, $this->Session->read('Auth.User.id'));
			if ($this->request->data) {
				unset($this->request->data['User']['password']);
			}
		}
		$personList = $this->Person->find("all");
		$this->set('personList', $personList);
	}

	public function profile() {
		$actualUser = $this->Session->read('Auth.User');

		$this->Commission->recursive = 1;
		$commissions = $this->Commission->find('all', array('conditions' => array('Commission.fk_person_id' => $actualUser['Person']['id'])));
		$myCommissions = array();
		$myMarketIds = array();
		$totalCommissionValue = 0;
		foreach ($commissions as $commission) {
			// odmena pre maklerov - 1 a pre ponukacov - 2
			if (in_array($commission['Commission']['type'], array(1, 2))) {
				$type = Market::MT_OFFER;
				$marketId = $commission['Transfer']['fk_offer_id'];
			} else {
				$type = Market::MT_DEMAND;
				$marketId = $commission['Transfer']['fk_demand_id'];
			}
			$myMarketIds[] = $marketId;
			$value = $commission['Commission']['value'];
			$myCommissions[$type][$marketId] = $value;
			$totalCommissionValue += $value;
			$this->set('myCommissions', $myCommissions);
		}
		$markets = array();
		if (!empty($myMarketIds)) {
			$conditions = array('Market.status' => Market::STATUS_FINISHED_SUCCESSFULLY, 'Market.id' => $myMarketIds);

			$this->Market->recursive = 0;
			$markets = $this->Market->find('all' , array('conditions' => $conditions, 'order' => 'Market.id DESC'));
		}
		$this->set('markets', $markets);
		$this->set('totalCommissionValue', $totalCommissionValue);
	}
	
	public function delete($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			$this->setFlashError('Záznam nebol nájdený.');
		} else {
			if ($this->User->delete()) {
				$this->setFlashSuccess('Záznam bol zmazaný z databázy.');
			} else {
				$errors = array_merge(array('Záznam nebol zmazaný z databázy.'), Errors::getErrors());
				$message = implode("<br />", $errors);
				$this->setFlashError($message);
			}
		}
		$this->redirect(array('action' => 'index'));
	}

	public function login() {
		if ($this->Auth->login() === TRUE) {
			$actualUser = $this->Session->read('Auth.User');
			if ($actualUser['restricted_access'] == 1) {
				$this->logout('Vaše konto bolo zablokované. Kontaktujte administrátora systému.');
			} else {
				$this->redirect(array('controller' => 'pages', 'action' => 'index'));
			}
		}

		if ($this->request->is('post')) {
			if ($this->Auth->login()) {
				$actualUser = $this->Session->read('Auth.User');
				if ($actualUser['restricted_access'] == 1) {
					$this->logout('Vaše konto bolo zablokované. Kontaktujte administrátora systému.');
				} else {
					$this->redirect($this->Auth->redirect());
				}
			} else {
				$this->setFlashError('Zadali ste nesprávne používateľské meno alebo heslo.');
				$this->redirect(array('action' => 'login'));
			}
		}
	}

	public function logout($message = NULL) {
		$this->Auth->logout();
		if ($message) {
			$this->setFlashWarning($message);
		} else {
			$this->setFlashSuccess('Boli ste odhlásený zo systému.');
		}
		$this->redirect(array('action' => 'login'));
	}
	
	public function happybirthday() {
		$conditions = array(
			'Person.birth_day' => date('j'),
			'Person.birth_month' => date('n'),
		);
		
		$personList = $this->Person->find('all', array('conditions' => $conditions));
		
		$message = '<p>Krásny narodeninový deň s prianím zdravia, pokoja, harmónie a úspechu prajú:</p>';
		$message .= '<p>Mgr. Miloš Ortuta</p>';
		$message .= '<p>Mgr. Michal Kmec</p>';
		$message .= '<p>Ľubomír Drábik</p>';
		$message .= '<p>A tím spoločnosti My New Home</p>';
		$count = 0;
		foreach ($personList as $person) {
			$this->sendMail($person['Person']['email'], 'Blahoželanie k narodeninám', $message);
			$count++;
		}
		echo $count . "\n";
		echo 'DONE';
		exit();
	}
	
	public function happynameday() {
		$conditions = array(
			'Name.day' => date('j'),
			'Name.month' => date('n'),
		);
		
		$nameList = $this->Name->find('all', array('conditions' => $conditions));
		
		$names = array();
		foreach ($nameList as $name) {
			$names[] = $name['Name']['name'];
		}
		
		$conditions = array(
			'Person.name' => $names
		);
		$personList = $this->Person->find('all', array('conditions' => $conditions));
		
		$message = '<p>Krásny meninový deň s prianím zdravia, pokoja, harmónie a úspechu prajú:</p>';
		$message .= '<p>Mgr. Miloš Ortuta</p>';
		$message .= '<p>Mgr. Michal Kmec</p>';
		$message .= '<p>Ľubomír Drábik</p>';
		$message .= '<p>A tím spoločnosti My New Home</p>';
		$count = 0;
		foreach ($personList as $person) {
			$this->sendMail($person['Person']['email'], 'Blahoželanie k meninám', $message);
			$count++;
		}
		echo $count . "\n";
		echo 'DONE';
		exit();
	}
	
}

?>